package com.lxyk.yygh.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lxyk.yygh.model.cmn.Dict;
import com.lxyk.yygh.service.DictService;
import com.lxyk.yygh.vo.cmn.DictEeVo;
import com.sun.org.apache.xpath.internal.operations.Div;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.BeanUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

//读取数据监听器
@Slf4j
//不能被spring管理，要每次读取excel都要new,
public class DataListener extends AnalysisEventListener<DictEeVo> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<Dict> cachedDataList =new ArrayList<>(BATCH_COUNT);

    //存到数据库
    private DictService dictService;

    public DataListener(DictService dictService) {

        this.dictService=dictService;
    }


    /**
     * 每一条数据解析都会调用
     * @param dictEeVo
     * @param analysisContext
     */
    @Override
    public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) {

        Dict dict = new Dict();
        BeanUtils.copyProperties(dictEeVo,dict);
        //默认为1
        dict.setIsDeleted(0);
        cachedDataList.add(dict);
        //达到数据库存储
        if(cachedDataList.size()>=BATCH_COUNT){
            dictService.saveBatch(cachedDataList);
            //清空list
            cachedDataList=new ArrayList<>(BATCH_COUNT);
        }


    }

    /**
     * 数据解析完成调用
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
       //解析完了保存到数据库
        dictService.saveBatch(cachedDataList);
    }
}
